package com.bridgeintelligent.tag.webserver.dim.mgmt.service.dim;

import cn.hutool.json.JSONUtil;
import com.bridgeintelligent.tag.constants.DimCofig;
import com.bridgeintelligent.tag.constants.ExceptionCodes;
import com.bridgeintelligent.tag.constants.TagConstants;
import com.bridgeintelligent.tag.customer.mapper.CustomersMapper;
import com.bridgeintelligent.tag.customer.service.CustomersService;
import com.bridgeintelligent.tag.mapper.*;
import com.bridgeintelligent.tag.user.mgmt.pojo.User;
import com.bridgeintelligent.tag.utils.DateHelper;
import com.bridgeintelligent.tag.utils.SecurityHelper;
import com.bridgeintelligent.tag.webserver.dim.mgmt.api.*;
import com.bridgeintelligent.tag.webserver.dim.mgmt.api.enums.CatalogEnum;
import com.bridgeintelligent.tag.webserver.dim.mgmt.api.indexdim.DimInfoModel;
import com.bridgeintelligent.tag.webserver.dim.mgmt.api.indexdim.IndexDimModel;
import com.bridgeintelligent.tag.webserver.dim.mgmt.api.model.DimNumModel;
import com.bridgeintelligent.tag.webserver.dim.mgmt.service.dim.vo.DimVO;
import com.bridgeintelligent.tag.webserver.dim.mgmt.service.es.IEsInfoService;
import com.bridgeintelligent.tag.webserver.workflow.repository.InstanceMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wayneleo.quickstart.framework.ExceptionCode;
import com.wayneleo.quickstart.framework.IDGenerator;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.bridgeintelligent.tag.constants.TagConstants.SENSITIVE_CATALOG;

/**
 * Created by JackCheung on 2019/9/9 10:10 PM.
 */
@Slf4j
@AllArgsConstructor
@Service
public class DimService implements IDimService {

    private DimMapper dimMapper;
    private ObjectMapper objectMapper;
    private DimItemMapper dimItemMapper;
    private DimDelMapper dimDelMapper;
    private DimItemDelMapper dimItemDelMapper;
    private CatalogMapper catalogMapper;
    private DimMineMapper dimMineMapper;
    private DepartmentMapper departmentMapper;
    private DimThemeMapper dimThemeMapper;
    private CustomersMapper customersMapper;
    private CustomersService customersService;
    private EsTimeDataMapper esTimeDataMapper;
    private static final String MONTH_FORMAT = "%s年%s月";
    private static final String DAY_FORMAT="%s年%s月%s日";
    private static final String COUNT_DOWN_FORMAT = "当前月份%s";

    private static final String FIRST_INDEX = "1";
    private IndexDimMapper indexDimMapper;

    private DimCombinatinMapper dimCombinatinMapper;

    private InstanceMapper instanceMapper;
    private IEsInfoService esInfoService;
    @Override
    public DimRep detail(String dimId) {
        DimData dim = dimMapper.detail(dimId);
        Map<String, String> themeMap = getThemeMap();
        dim.setTheme(themeMap.get(dim.getTheme()) != null ? themeMap.get(dim.getTheme()) : dim.getTheme());
        List<DimItem> list = dimItemMapper.list(dimId);
        DimVO dimVO = new DimVO(dim, list);
        return new DimRep<>(dimVO, BaseCode.SUCCESS);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public DimRep add(String dimJson) {
        try {
            DimVO dimVO = objectMapper.readValue(dimJson, DimVO.class);
            DimData dim = dimVO.getDim();
            List<DimItem> list = dimVO.getList();
            if (StringUtils.isEmpty(dim.getCatalogId())) {
                return new DimRep(BaseCode.FAIL, "请选择标签目录！");
            }
            DimData dbData = dimMapper.detail(dim.getDimId());
            if (dbData != null) {
                return new DimRep(BaseCode.FAIL, "新增失败！标签ID重复！");
            }
            int result = dimMapper.findExits(dim.getDimName());
            if (result > 0) {
                return new DimRep(BaseCode.FAIL, "新增失败！标签名称重复！");
            }

            String date = format(new Date());
//            String dimId = IdWorker.nextId();
            String dimId = dim.getDimId()
                              .toLowerCase();
            User user = SecurityHelper.currentUser();
            String department = user.getDepartment();
            dim.setCreateTime(date)
               .setUptTime(date)
               .setDimId(dimId)
               .setDimLargeType(DimCofig.BASE_DIM)
               .setState(DimCofig.DIM_USEING)
               .setDepartment(department)
               .setIscollect(false);

            //校验移动标签目录的权限
            Map<String,String> map = checkPower(dim.getDimLargeType(),dim.getCatalogId());
            if ("FALSE".equals(map.get("FLAG"))){
                //不能移动
                return new DimRep(BaseCode.FAIL, map.get("MSG"));
            }

            dimMapper.add(dim);
            if (CollectionUtils.isNotEmpty(list)) {
                list.forEach(dimItem -> {
                    dimItem.setDimId(dimId);
                    dimItem.setId(IdWorker.nextId());
                    dimItem.setUpdateDate(date);
                    dimItemMapper.add(dimItem.getId(), dimItem.getDimId(), dimItem.getItemNo(), dimItem.getItemName(), dimItem.getUpdateDate());
                });
//                dimItemMapper.adds(list);
            }
            return new DimRep<>(new DimVO(dim, list), BaseCode.SUCCESS, "新增成功");
        } catch (IOException e) {
            e.printStackTrace();
            throw new DimException(new ExceptionCode(999, e.getMessage()));
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public DimRep addEntity(DimVO dimVO) {
        try {
            DimData dim = dimVO.getDim();
            List<DimItem> list = dimVO.getList();
            if (StringUtils.isEmpty(dim.getCatalogId())) {
                return new DimRep(BaseCode.FAIL, "请选择标签目录！");
            }
            DimData dbData = dimMapper.detail(dim.getDimId());
            if (dbData != null) {
                return new DimRep(BaseCode.FAIL, "新增失败！标签ID重复！");
            }
            int result = dimMapper.findExits(dim.getDimName());
            if (result > 0) {
                return new DimRep(BaseCode.FAIL, "新增失败！标签名称重复！");
            }

            String date = format(new Date());
            String dimId = dim.getDimId()
                    .toLowerCase();
            User user = SecurityHelper.currentUser();
            String department = user.getDepartment();
            dim.setCreateTime(date)
                    .setUptTime(date)
                    .setDimId(dimId)
                    .setDimLargeType(DimCofig.BASE_DIM)
                    .setState(DimCofig.DIM_USEING)
                    .setDepartment(department)
                    .setIscollect(false);

            //校验移动标签目录的权限
            Map<String,String> map = checkPower(dim.getDimLargeType(),dim.getCatalogId());
            if ("FALSE".equals(map.get("FLAG"))){
                //不能移动
                return new DimRep(BaseCode.FAIL, map.get("MSG"));
            }

            dimMapper.add(dim);
            if (CollectionUtils.isNotEmpty(list)) {
                list.forEach(dimItem -> {
                    dimItem.setDimId(dimId);
                    dimItem.setId(IdWorker.nextId());
                    dimItem.setUpdateDate(date);
                    dimItemMapper.add(dimItem.getId(), dimItem.getDimId(), dimItem.getItemNo(), dimItem.getItemName(), dimItem.getUpdateDate());
                });
            }
            return new DimRep<>(new DimVO(dim, list), BaseCode.SUCCESS, "新增成功");
        } catch (Exception e) {
            e.printStackTrace();
            throw new DimException(new ExceptionCode(999, e.getMessage()));
        }
    }

    /**
     * 启用停用标签
     *
     * @param state
     * @param dimId
     * @return
     */
    @Override
    public DimRep start(String state, String dimId) {
        try {
            //若是停用标签
            if ("02".equals(state)) {
                //通过dimId查找customersIds
                List<String> customersIds = customersService.findCustomersIdsByDimId(dimId);
                if (customersIds != null && !customersIds.isEmpty()) {
                    throw new DimException(ExceptionCodes.DIMFREE_90003);
                }
                int count = dimCombinatinMapper.countUseds(dimId);
                if (count>0) {
                    throw new DimException(ExceptionCodes.DIMFREE_90003);
                }
            }
            //修改标签状态
            dimMapper.startOrStop(state, dimId);
            return new DimRep(BaseCode.SUCCESS, "01".equals(state) ? "标签启用成功" : "标签停用成功");
        } catch (DimException e) {
            return new DimRep(e.getCode(), e.getMessage());
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public DimRep update(String dimJson) {
        DimVO dimVO;
        try {
            dimVO = objectMapper.readValue(dimJson, DimVO.class);
            DimData dim = dimVO.getDim();
            List<DimItem> list = dimVO.getList();
            if (StringUtils.isEmpty(dim.getCatalogId())) {
                return new DimRep(BaseCode.FAIL, "请选择标签目录！");
            }

            //校验移动标签目录的权限
            Map<String,String> map = checkPower(dim.getDimLargeType(),dim.getCatalogId());
            if ("FALSE".equals(map.get("FLAG"))){
                //不能移动
                return new DimRep(BaseCode.FAIL, map.get("MSG"));
            }

            DimData oldDim = dimMapper.detail(dim.getDimId());
            String oldName = oldDim.getDimName();
            String dimName = dim.getDimName();
            if (dimName != null && !oldName.equals(dimName)) {
                int result = dimMapper.findExits(dim.getDimName());
                if (result > 0) {
                    return new DimRep(BaseCode.FAIL, "标签名称重复！");
                }
            }
            String date = format(new Date());
            String dimId = dim.getDimId();
            dim.setUptTime(date);
            dim.setState(DimCofig.DIM_USEING);
            User user = SecurityHelper.currentUser();
            String userId = user.getUserId();
            dim.setCreaterId(userId);
            dim.setIscollect(oldDim.isIscollect());
            dim.setSortNum(oldDim.getSortNum());
            dimMapper.update(dim);
            if (!CollectionUtils.isEmpty(list)) {
                dimItemMapper.delByDimId(dimId);
                list.forEach(dimItem -> {
                    dimItem.setDimId(dimId);
                    dimItem.setId(IdWorker.nextId());
                    dimItem.setUpdateDate(date);
                    dimItemMapper.add(dimItem.getId(), dimItem.getDimId(), dimItem.getItemNo(), dimItem.getItemName(), dimItem.getUpdateDate());
                });
//                dimItemMapper.adds(list);
            }
            return new DimRep<>(new DimVO(dim, list), BaseCode.SUCCESS, "修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            throw new DimException(new ExceptionCode(999, e.getMessage()));
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public DimRep updateEntity(DimVO dimVO) {
        try {
            DimData dim = dimVO.getDim();
            List<DimItem> list = dimVO.getList();
            if (StringUtils.isEmpty(dim.getCatalogId())) {
                return new DimRep(BaseCode.FAIL, "请选择标签目录！");
            }

            //校验移动标签目录的权限
            Map<String,String> map = checkPower(dim.getDimLargeType(),dim.getCatalogId());
            if ("FALSE".equals(map.get("FLAG"))){
                //不能移动
                return new DimRep(BaseCode.FAIL, map.get("MSG"));
            }

            DimData oldDim = dimMapper.detail(dim.getDimId());
            String oldName = oldDim.getDimName();
            String dimName = dim.getDimName();
            if (dimName != null && !oldName.equals(dimName)) {
                int result = dimMapper.findExits(dim.getDimName());
                if (result > 0) {
                    return new DimRep(BaseCode.FAIL, "标签名称重复！");
                }
            }
            String date = format(new Date());
            String dimId = dim.getDimId();
            dim.setUptTime(date);
            dim.setState(DimCofig.DIM_USEING);
            User user = SecurityHelper.currentUser();
            String userId = user.getUserId();
            dim.setCreaterId(userId);
            dim.setIscollect(oldDim.isIscollect());
            dim.setSortNum(oldDim.getSortNum());
            dimMapper.update(dim);
            if (!CollectionUtils.isEmpty(list)) {
                dimItemMapper.delByDimId(dimId);
                list.forEach(dimItem -> {
                    dimItem.setDimId(dimId);
                    dimItem.setId(IdWorker.nextId());
                    dimItem.setUpdateDate(date);
                    dimItemMapper.add(dimItem.getId(), dimItem.getDimId(), dimItem.getItemNo(), dimItem.getItemName(), dimItem.getUpdateDate());
                });
//                dimItemMapper.adds(list);
            }
            return new DimRep<>(new DimVO(dim, list), BaseCode.SUCCESS, "修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            throw new DimException(new ExceptionCode(999, e.getMessage()));
        }
    }

    /**
     * 是否有移动标签目录的权限
     * @param dimLargeType
     * @param catalogId
     * @return
     */
    private Map<String,String > checkPower(String dimLargeType,String catalogId){
        Map<String,String> map = new HashMap();
        DimCatalog catalog = catalogMapper.findByCataName(TagConstants.PRIVATE_CATALOGID);
        if (catalog == null){
            map.put("FLAG","FALSE");
            map.put("MSG","私有标签目录不存在");
        }
        if (catalog.getId().equals(catalogId)){ //如果目录是私有标签目录
            if (DimCofig.FREE_DIM.equals(dimLargeType) || DimCofig.GROUP_DIM.equals(dimLargeType)){
                //如果是定制标签或者组合标签是允许移动到私有标签目录
                map.put("FLAG","TRUE");
                map.put("MSG","可以移动");
            }else{
                map.put("FLAG","FALSE");
                map.put("MSG","非定制标签、组合标签不可移入私有标签目录");
            }
        }else{ //如果目录不是私有标签目录
            if (DimCofig.FREE_DIM.equals(dimLargeType) || DimCofig.GROUP_DIM.equals(dimLargeType)){
                map.put("FLAG","FALSE");
                map.put("MSG","定制标签、组合标签不可移入非私有标签目录");
            }else{
                map.put("FLAG","TRUE");
                map.put("MSG","可以移动");
            }
        }
        return map;
    }

    @Override
    public DimRep list(Integer pageNumber, Integer pageSize, String theme, String dimName, String department, String state, String createTimeStart, String createTimeEnd, String uptTimeStart, String uptTimeEnd, String catalogId, String businessDepartment) {
        if (StringUtils.isNotEmpty(createTimeStart)) {
            createTimeStart = createTimeStart + " 00:00:00";
        }
        if (StringUtils.isNotEmpty(createTimeEnd)) {
            createTimeEnd = createTimeEnd + " 23:59:59";
        }
        if (StringUtils.isNotEmpty(businessDepartment)) {
            String result = departmentMapper.findOne(businessDepartment);
            businessDepartment = result == null ? businessDepartment : result;
        }
        if (StringUtils.isNotEmpty(theme)) {
            String result = getReversalThemeMap().get(theme);
            theme = result == null ? theme : result;
        }
        List<String> cataIds = null;
        if (catalogId != null) {
            cataIds = new ArrayList<>();
            cataIds.add(catalogId);
            List<DimCatalog> nexCataLogs = catalogMapper.findNext(catalogId);
            if (!CollectionUtils.isEmpty(nexCataLogs)) {
                cataIds.addAll(nexCataLogs.stream()
                                          .map(DimCatalog::getId)
                                          .collect(Collectors.toList()));
            }
        }
        Page page = PageHelper.startPage(pageNumber, pageSize);
        List<DimData> list = dimMapper.findList(theme, dimName, department, state, createTimeStart, createTimeEnd, uptTimeStart, uptTimeEnd, cataIds, businessDepartment);
        Map<String, String> themeMap = getThemeMap();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(calendar.MONTH, -1);
        String temp = format(calendar.getTime());
        list.forEach(dim -> {
            dim.setTheme(themeMap.get(dim.getTheme()) != null ? themeMap.get(dim.getTheme()) : dim.getTheme());
            if (temp.compareTo(dim.getUptTime()) < 1) {
                dim.setIsnew(true);
            } else {
                dim.setIsnew(false);
            }
        });
        DimPage<DimData> dimDimPage = new DimPage<>();
        dimDimPage.setContent(list);
        dimDimPage.setTotalPages(page.getPages());
        dimDimPage.setTotalElements(page.getTotal());
        dimDimPage.setSize(page.getPageSize());
        dimDimPage.setRequestPager(pageNumber);
        return new DimRep<>(dimDimPage, BaseCode.SUCCESS);
    }

    /**
     * 删除标签
     *
     * @param dimId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public DimRep del(String dimId) {
        User user = SecurityHelper.currentUser();
        //删除收藏标签
        dimMineMapper.del(dimId, user.getUserId());
        //删除授权列表
        //修改客群为失效状态
        //通过dimId查找customersIds
        List<String> customersIds = customersService.findCustomersIdsByDimId(dimId);
        if (customersIds != null && !customersIds.isEmpty()) {
            for (String customersId : customersIds) {
                //将客群设置为失效
                customersMapper.updateCustomersStatus(customersId, "02");
            }
        }
        DimData dimData = dimMapper.detail(dimId);
        //判断是否是修改目录
        DimDataDel dimDataDel = new DimDataDel();
        try {
            fatherToChild(dimData, dimDataDel);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        dimDataDel.setDelDate(format(new Date()));
        dimDataDel.setDimDelId(IDGenerator.gen());
        //如果是组合标签或者自定义标签将dim_data表的state置为03表示逻辑删除
        if ("04".equals(dimData.getDimLargeType()) || "02".equals(dimData.getDimLargeType())){
            dimMapper.updateStateId(dimId);
        }else{
            dimMapper.del(dimId);
        }
        dimDelMapper.insert(dimDataDel);
        dimItemDelMapper.insert(dimId);
        dimItemMapper.delByDimId(dimId);

        //如果是组合标签，删除相关的表数据
        if ("04".equals(dimData.getDimLargeType())){
            delCombinationInfo(dimId);
        }
        return new DimRep(BaseCode.SUCCESS);
    }

    @Override
    public DimRep inCatalogList(String dimName) {
        List<String> list = dimMapper.inCatalogList(dimName);
        return new DimRep<>(list, BaseCode.SUCCESS);
    }

    @Override
    public DimRep dimList(Integer pageNumber, Integer pageSize, String theme, String dimName, String department, String state, String createTimeStart, String createTimeEnd, String uptTimeStart, String uptTimeEnd, String catalogId, String businessDepartment) {
        if (StringUtils.isNotEmpty(createTimeStart)) {
            createTimeStart = createTimeStart + " 00:00:00";
        }
        if (StringUtils.isNotEmpty(createTimeEnd)) {
            createTimeEnd = createTimeEnd + " 23:59:59";
        }
//        if (StringUtils.isNotEmpty(uptTimeStart)) {
//            uptTimeStart = uptTimeStart + " 00:00:00";
//        }
//        if (StringUtils.isNotEmpty(uptTimeEnd)) {
//            uptTimeEnd = uptTimeEnd + " 23:59:59";
//        }
        if (StringUtils.isNotEmpty(businessDepartment)) {
            String result = departmentMapper.findOne(businessDepartment);
            businessDepartment = result == null ? businessDepartment : result;
        }
        if (StringUtils.isNotEmpty(theme)) {
            String result = getReversalThemeMap().get(theme);
            theme = result == null ? theme : result;
        }
        List<String> cataIds = null;
        if (catalogId != null) {
            cataIds = new ArrayList<>();
            cataIds.add(catalogId);
            List<DimCatalog> nexCataLogs = catalogMapper.findNext(catalogId);
            if (!CollectionUtils.isEmpty(nexCataLogs)) {
                cataIds.addAll(nexCataLogs.stream()
                                          .map(DimCatalog::getId)
                                          .collect(Collectors.toList()));
            }
        }
        User user = SecurityHelper.currentUser();
        List<DimData> list;
        String current = DateFormatUtils.format(new Date(), DateFormatUtils.ISO_8601_EXTENDED_DATE_FORMAT.getPattern());
        String dataTime = esInfoService.dataTime();
        List<DimCatalog> sensitive = getSensitive();
        Page page = PageHelper.startPage(pageNumber, pageSize);
        if(catalogId == null){
            list = dimMapper.findAllList(current,theme, dimName, department, state, createTimeStart,
                    createTimeEnd,
                    uptTimeStart, uptTimeEnd, cataIds, businessDepartment,user.getUserId(),dataTime,sensitive);
        }else if(StringUtils.equals(CatalogEnum.SHARED_TAG.getCatalogId(),catalogId)){
            list = dimMapper.findPartSharedList(current,theme, dimName, department, state, createTimeStart,
                    createTimeEnd,
                    uptTimeStart, uptTimeEnd, cataIds, businessDepartment,user.getUserId(), dataTime);
        }else{
            list = dimMapper.findPrivateAndSharedList(current,theme, dimName, department, state, createTimeStart, createTimeEnd,
                    uptTimeStart, uptTimeEnd, cataIds, businessDepartment,user.getUserId(),dataTime, sensitive);
        }
        Map<String, String> themeMap = getThemeMap();
        List<String> dimMineList = mineDimList();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.MONTH, -1);
        String temp = format(calendar.getTime());
        list.forEach(dim -> {
            dim.setTheme(themeMap.get(dim.getTheme()) != null ? themeMap.get(dim.getTheme()) : dim.getTheme());
            if (dimMineList.contains(dim.getDimId())) {
                if (!dim.isIscollect()) {
                    dim.setIscollect(true);
                    dimMapper.update(dim);
                }
                dim.setIscollect(true);
            }
            if (temp.compareTo(dim.getUptTime()) < 1) {
                dim.setIsnew(true);
            }
        });
        DimPage<DimData> dimDimPage = new DimPage<>();
        dimDimPage.setContent(list);
        dimDimPage.setTotalPages(page.getPages());
        dimDimPage.setTotalElements(page.getTotal());
        dimDimPage.setSize(page.getPageSize());
        dimDimPage.setRequestPager(pageNumber);
        return new DimRep<>(dimDimPage, BaseCode.SUCCESS);
    }

    public List<DimCatalog> getSensitive() {
        DimCatalog sensitive = catalogMapper.findByCataName(SENSITIVE_CATALOG);
        if(sensitive==null){
            return null;
        }
        List<DimCatalog> result = new ArrayList<>();
        result.add(sensitive);
        List<DimCatalog> nexCataLogs = catalogMapper.findNext(sensitive.getId());
        if (CollectionUtils.isNotEmpty(nexCataLogs)) {
            result.addAll(nexCataLogs);
        }
        return result;
    }

    @Override
    public DimRep esTimeData() {
        List<EsTimeData> list = esTimeDataMapper.findAll();
        Map<String, List<EsTimeData>> offLineMap= fetchData(list);
        EsTimeDataRsp esTimeDataRsp = fetchRsp(list, offLineMap);
        return new DimRep<>(esTimeDataRsp, BaseCode.SUCCESS);
    }

    private  Map<String, List<EsTimeData>>  fetchData(  List<EsTimeData> list) {
        Map<String, List<EsTimeData>> result = new HashMap<>(list.size());
        list.stream()
            .filter(dateBean -> !dateBean.isRealTime())
            .sorted(Comparator.comparing(EsTimeData::getTime))
            .forEach(esTimeData -> {
                String year = esTimeData.getTime().substring(0, 4);
                if (result.containsKey(year)) {
                    setMonth(esTimeData);
                    result.get(year).add(esTimeData);
                } else {
                    List<EsTimeData> tmpList = new ArrayList<>();
                    setMonth(esTimeData);
                    tmpList.add(esTimeData);
                    result.put(year, tmpList);
                }
            });
        return result;
    }

    @Override
    public DimRep esTimeOutput() {
        List<EsTimeData> list = esTimeDataMapper.findAll();
        Map<String, List<EsTimeData>> offLineMap= fetchData(list);
        list.stream()
            .filter(EsTimeData::isRealTime)
            .forEach(esTimeData -> {
                String year = esTimeData.getTime().substring(0, 4);
                setMonthDay(esTimeData);
                if( Objects.isNull(offLineMap.get(year))){
                    ArrayList<EsTimeData> esTimeDataArrayList = new ArrayList<EsTimeData>();
                    offLineMap.put(year, esTimeDataArrayList);
                }
                offLineMap.get(year).add(esTimeData);
            });
        EsTimeDataRsp esTimeDataRsp = new EsTimeDataRsp(offLineMap,null);
        return new DimRep<>(esTimeDataRsp, BaseCode.SUCCESS);
    }

    @Override
    public DimRep esTimeLast() {
        EsTimeData result = esTimeDataMapper.findRealTime();
        return new DimRep<>(result,BaseCode.SUCCESS);
    }

    private void setMonthDay(EsTimeData esTimeData) {
        String year = StringUtils.substring(esTimeData.getTime(), 0, 4);
        String month = StringUtils.substring(esTimeData.getTime(), 4,6);
        String day=StringUtils.substring(esTimeData.getTime(),6);
        String zero = "0";
        String timeName = month.startsWith(zero) ? String.format(DAY_FORMAT, year, month.substring(1),day) : String.format(DAY_FORMAT, year, month,day);
        esTimeData.setTimeName(timeName);
    }

    @Override
    public void delCombinationInfo(String combinationId) {
        dimCombinatinMapper.delUpt(combinationId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DimRep stop(String dimId) {
        // 相关组合标签停用
        dimCombinatinMapper.stopByDimId(dimId, DateHelper.currentDateTime());
        // 标签停用
        dimMapper.startOrStop("02", dimId);
        // 相关客群失效
        customersMapper.stopByDimId(dimId, DateHelper.currentDateTime());
        return new DimRep<>(BaseCode.SUCCESS);
    }

    @Override
    public DimRep newEsTime(String indexId) {

        List<EsTimeModel> timeList = esTimeDataMapper.indexAllTime(indexId);
        timeList.forEach(e->{
            if (1 == e.getTimeType()){
                e.setRealTime(true);
            }else{
                e.setRealTime(false);
            }
        });
        Map<String, List<EsTimeModel>> year2time = timeList.stream().collect(Collectors.groupingBy(x -> x.getTime().substring(0, 4)));
        return new DimRep(year2time,BaseCode.SUCCESS,"查询成功");
    }

    @Override
    public DimRep mapEsTime(String indexId) {
        List<EsTimeModel> timeList = esTimeDataMapper.indexAllTime(indexId);
        Map<String,String> map = new HashMap<>(30);
        timeList.forEach(model->{
            map.put(model.getTime(),model.getSymbol());
        });
        return new DimRep(map,BaseCode.SUCCESS,"查询成功");
    }

    @Override
    public List<DimNumModel> numberDimList(String dimName, String dimId,String indexId) {
        //根据索引ID获取对应标签配置信息
        List<String> indexDimList = new ArrayList<>();
        if (!FIRST_INDEX.equals(indexId)){
            IndexDimModel indexDim = indexDimMapper.findIndexDimById(Integer.valueOf(indexId));
            if (indexDim != null && !StringUtils.isEmpty(indexDim.getIndexDim())){
                List<DimInfoModel> infoModels = JSONUtil.toList(indexDim.getIndexDim(), DimInfoModel.class);
                List<String> dimIds = infoModels.stream().map(e -> e.getDimId()).collect(Collectors.toList());
                indexDimList.addAll(dimIds);
            }
        }
        return dimMapper.numberDimList(dimName,dimId,indexDimList);
    }


    private EsTimeDataRsp fetchRsp(List<EsTimeData> list, Map<String, List<EsTimeData>> offLineMap) {
        int length = 13;
        List<EsTimeData> realTimeList = list.stream()
                                            .map(esTimeData -> new EsTimeData(esTimeData.getTime(), esTimeData.isRealTime()))
                                            .sorted(Comparator.comparing(EsTimeData::getTime).reversed())
                                            .collect(Collectors.toList());
        for (int i = 0; i < realTimeList.size(); i++) {
            if (i != 0) {
                realTimeList.get(i).setCountDown(String.format(COUNT_DOWN_FORMAT, "-" + i));
            } else {
                realTimeList.get(i).setCountDown(String.format(COUNT_DOWN_FORMAT, ""));
            }
            realTimeList.get(i).setPosition(0 - i);
        }
        if (realTimeList.size() > length) {
            return new EsTimeDataRsp(offLineMap, realTimeList.subList(0, length));
        } else {
            return new EsTimeDataRsp(offLineMap, realTimeList);
        }
    }

    private void setMonth(EsTimeData esTimeData) {
        String year = StringUtils.substring(esTimeData.getTime(), 0, 4);
        String month = StringUtils.substring(esTimeData.getTime(), 4);
        String zero = "0";
        String timeName = month.startsWith(zero) ? String.format(MONTH_FORMAT, year, month.substring(1)) : String.format(MONTH_FORMAT, year, month);
        esTimeData.setTimeName(timeName);
    }

    private List<String> mineDimList() {
        User user = SecurityHelper.currentUser();
        String userId = user.getUserId();
        return dimMineMapper.list(userId);
    }

    private Map<String, String> getThemeMap() {
        return dimThemeMapper.list()
                             .stream()
                             .collect(Collectors.toMap(DimTheme::getId, DimTheme::getName));
    }

    private Map<String, String> getReversalThemeMap() {
        return dimThemeMapper.list()
                             .stream()
                             .collect(Collectors.toMap(DimTheme::getName, DimTheme::getId));
    }

    private static String format(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return sdf.format(date);
        } catch (Exception e) {
            return null;
        }
    }
}
